var $ = window.$;
var jade = require('jade');
var Promise = require('bluebird');
var path = require('path');
var animate = require('../../util/animate');
var event = require('../../core/event');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var config = require('../../core/config');
var notify = require('../notify/ui');
var note = require('../note/manager');
var Log = require('../../util/logger');
var exec = require("child_process").execFile;
var _inited = false;


var ret = {
	init: function(){
		if(_inited){
			return;
		}
		this.uploading = false;  //正在上传
		this.cid = 0;
		this.mainPath = null;
		this.mainDir = null;
		//event.bind(event.events.key.up, 'upload_ui', this);
		event.lock('key', 'upload_ui');
		_inited = true;
	},

	setManager: function (ma) {
		this.manager = ma;
	},

	onEvent: function(e, param){
		/*if(param.key == 27){
			this.hide();
			return event.result.stopAll;
		}*/
	},

	doUpload: function() {
		if(this.pending.length == 0){
			this.finishUpload();
			return;
		}
		var idx = this.pending.shift();
		var file = this.files[idx];
		var hash = this.md5[idx];
		var self = this;

		this.manager._getUploadSign({
			name: hash,
			cid: this.cid,
			ver: 2
		}).then(function(data) {
			if(!data || data.code == -1){
				notify.addNotify({
					msg: config.i18n('err15')
				});
				return this.emptyFunc();
			}else if(data.code == -2){
				notify.addNotify({
					msg: config.i18n('err16')
				});
				return this.emptyFunc();
			}else if(data.code == -3){
				notify.addNotify({
					msg: config.i18n('err17')
				});
				return this.emptyFunc();
			}else if(data.code == -4){
				notify.addNotify({
					msg: config.i18n('err18')
				});
				return this.emptyFunc();
			}else if(data.code == 0){
				//参数正常, 传到cdn
				return self.manager._uploadToCDN({
					file:{
						file: file,
						content_type : 'application/octet-stream'
					},
					policy: data.data.policy,
					signature: data.data.signature
				});
			}
		}).then(function(data) {
			if(!data || data.code != 200){
				if(data){
					Log.e("upload error: "+data.msg, "Upload");
				}else{
					Log.e("CDN no response", "Upload");
				}
				return this.emptyFunc(); //随便抛个错误
			}
			Log.i("Upload succ:"+self.files[idx], "Upload");
			//UI更新
			self.oldlist[hash] = true;
			self.parent.find('#dialog_upload_list li').eq(idx).removeClass('curr').addClass('done');
			var percent = (self.pendingCount - self.pending.length) * 100 / self.pendingCount;
			self.parent.find('#dialog_progress').css('width', percent +'%');
			setTimeout(function() {
				self.doUpload();
			}, 50);  //50ms给UI刷新
		}).catch(function(e) {
			//出错就中断
			Log.e("upload error: internal", "Upload");
			self.pending.unshift(idx); //重新塞回去
			self.finishUpload();
		});
	},


	startUpload: function () {
		//先检查一下能否开始
		if(!this.files || !this.md5){
			return;  //这是错误, 不用提示
		}
		var curr = this.parent.find('#dialog_upload_list .curr');
		if(!curr.size()){
			notify.addNotify({
				msg: config.i18n('err14')
			});
			return;
		}
		var id = +this.parent.find("#upload_id").val();
		if(!id){
			notify.addNotify({
				msg: config.i18n('err14')
			});
			return;
		}
		this.cid = id;

		var btn = this.parent.find(".g_bt span");
		btn.eq(0).html("Wait");
		btn.eq(1).hide();
		this.uploading = true;

		notify.showWaiting(true);
		var len = curr.size();
		this.pending = [];
		this.pendingCount = len;
		for(var i=0;i<len;i++){
			this.pending.push(curr.eq(i).index());  //把选择的文件序号加入
		}
		Log.i("Start upload, count:"+len, "Upload");
		this.doUpload();
	},

	finishUpload: function() {
		if(this.pending.length){
			//还有剩余file, 未成功
			notify.showWaiting(false);
			this.uploading = false;

			this.parent.find('#dialog_progress').css('width', '0');
			var btn = this.parent.find(".g_bt span");
			btn.eq(0).html("Start").show();
			btn.eq(1).show();
			notify.addNotify({
				msg: config.i18n("up08")
			});
			Log.i("Upload fail, left:"+this.pending.length, "Upload");
		}else{
			//成功, 上传最终列表
			var list = [];
			var newhash = '';
			for(var i=0;i<this.files.length;i++){
				var _name = path.basename(this.files[i]);
				list.push({
					name: _name,
					hash: this.md5[i],
					size: util.fileSize(this.files[i])
				});
				if(_name.indexOf(this.mainType) > 0){
					if(this.mainType == ".tja"){
						newhash = util.md5("0"+this.md5[i]+"0");
					}else{
						newhash = this.md5[i];
					}
				}
			}
			var conf = {
				cid: this.cid,
				raw: JSON.stringify(list),
				hash: newhash,
				ver: 2
			};
			//console.log("newhash:"+newhash);
			var self = this;
			this.manager._sendUploadConfirm(conf).then(function(data) {
				notify.showWaiting(false);
				self.uploading = false;
				self.parent.find('#dialog_progress').css('width', 0);

				var btn = self.parent.find(".g_bt span");
				btn.eq(1).show();

				if(!data || data.code != 0){
					if(data){
						Log.e("upload confirm fail:"+data.code, "Upload");
					}else{
						Log.e("upload confirm ", "Upload");
					}
					//前面检查过一次参数, 如果这里再发生错误, 一律是后台问题
					btn.eq(0).html("Start");
					notify.addNotify({
						msg: config.i18n('err15')
					});
				}else{
					btn.eq(0).hide();
					notify.addNotify({
						msg: config.i18n("up07")
					});
					Log.i("upload all success", "Upload");
				}

			});
		}
		//无论上传结果, 都要写入一次oldhash
		var oldhash = this.mainDir + '/old.hash';
		util.saveJson(oldhash, this.oldlist);
	},

	getID: function(){
		var conf = null;
		if(this.mainType == '.osu'){
			var osu_parse = require('../note/import/osu.js');
			conf = osu_parse.parseMeta(this.mainPath);
		}else if(this.mainType == '.tja'){
			var tja_parse = require('../note/import/tja.js');
			conf = tja_parse.parseMeta(this.mainPath);
			conf.mode = 5;
		}

		if(!conf){
			notify.addNotify({
				msg: config.i18n("err26"),
				err: true
			});
			return;
		}
		conf.type = 1;

		if(!conf.title || !conf.artist || !conf.version || !conf.length || conf.bpm == 0){
			notify.addNotify({
				msg: config.i18n("err26"),
				err: true
			});
			return;
		}

		notify.showWaiting(true);
		var self = this;
		this.manager._createOnlineChart(conf).then(function(data) {
			if(data){
				if(data.code == 0) {
					self.cid = data.data.cid;
					self.parent.find("#upload_id").val(self.cid);
				}else if(data.code == -1){
					notify.addNotify({
						msg: config.i18n("err27"),
						err: true
					});
				}else if(data.code == -2){
					notify.addNotify({
						msg: config.i18n("err13"),
						err: true
					});
				}else if(data.code < -10 || data.code != -1000){
					notify.addNotify({
						msg: config.i18n("err29"),
						err: true
					});
				}
			}
			notify.showWaiting(false);
		});
	},

	show: function(mainPath, type){
		this.mainPath = mainPath;
		this.mainType = type;
		this.mainDir = path.dirname(mainPath);
		var tmpl = jade.compileFile('./tmpl/upload/dialog_osu.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_upload');

		this.parent.find('#dialog_upload_list').on('click', 'li', function(e) {
			$(this).toggleClass('curr');
		});

		this.parent.on('click','.g_click', function(){
			var target = $(this);
			var type = target.data('type');
			if(type == 'close') {
				self.hide();
			}else if(type == 'ok'){
				if(self.uploading){
					return;
				}
				//启动上传
				self.startUpload();
			}else if(type == "id"){
				if(self.uploading || self.cid){
					return;
				}
				self.getID();
			}
		});

		this.parent.show();
		uiUtil.dialogInc();
		notify.showWaiting(true);
		animate.normalScaleIn(this.parent).then(function() {
			//数据量较大, 放到回调里来初始化
			//遍历主路径, 所有文件 ,除了osu
			return util.getAllFiles(path.dirname(mainPath));
		}).then(function(files){

			if (!files) {
				notify.showWaiting(false);
				notify.addNotify({
					msg: config.i18n('err14')
				});
				return;
			}
			var filename = path.basename(mainPath);
			//除了本身以外的osu要排除
			for(var i=files.length-1;i>=0;i--){
				var file = files[i];
				var ext = path.extname(file);
				if(ext == type && path.basename(file) != filename){
					files.splice(i, 1);
				}else if(ext == '.osb' || ext == '.db' || ext == '.hash'){
					files.splice(i, 1);
				}else if(path.basename(file)[0] == '.'){
					files.splice(i, 1);
				}
			}

			//meta
			self.files = files;  //全部文件列表

			//加载已上传文件列表
			var oldhash = self.mainDir + '/old.hash';
			var oldlist = util.loadJsonSync(oldhash) || {};
			self.oldlist = oldlist;
			//计算所有文件的hash
			var hash = [];
			for (var i = 0; i < self.files.length; i++) {
				hash.push(util.fileMd5(self.files[i]));
			}

			return Promise.all(hash);
		}).then(function (ret) {
			self.md5 = ret;  //全部文件对应的md5值
			var html = [];
			for(var i=0;i<ret.length;i++){
				var size = util.fileSize(self.files[i]);
				var cls = '';
				//没上传过, 或hash不一致
				if(!self.oldlist[ret[i]]){
					cls = 'class="curr"';
				}
				html.push('<li '+cls+'><span>'+path.basename(self.files[i])+'</span><i>'+util.getFormatSize(size)+'</i></li>');
			}

			self.parent.find('#dialog_upload_list').html(html.join(''));
			notify.showWaiting(false);
			if(self.mainType == '.tja'){
				notify.addNotify({
					msg: config.i18n("tip09")
				});
			}
		}).catch(function(e){
			Log.e(e, "Upload");
		});
		event.trigger(event.events.global.blur);

	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbind(event.events.key.up, 'upload_ui');
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;